//
//  TourOrderTableViewController.m
//  EasyToTesco2.0
//
//  Created by knew on 2017/5/5.
//  Copyright © 2017年 EasyToTesco. All rights reserved.
//

#import "TourOrderTableViewController.h"
#import "DateViewController.h"
#import "OrderPaymentController.h"
@interface TourOrderTableViewController ()<UIWebViewDelegate,UITableViewDelegate,UITableViewDataSource>

{
    NSString *numberString;
    BOOL _judgeFirst;
    NSString *_dataString;
}

@property (nonatomic,strong)UIButton *dataButton;

@property (nonatomic,strong)DateViewController *dateVC;

@property (nonatomic,strong)UITableView *tableView;

@property (nonatomic,strong)UIWebView *webView;

@property (nonatomic,strong)UILabel *priceLabel;

@property (nonatomic,strong)NSMutableArray *textFieldArray;

@end

@implementation TourOrderTableViewController

- (void)dealloc {
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT  - 64 - 49) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
//    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 30, 0)];
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.tableView];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    numberString = @"1";
    
    TourOrderLastView *lastView = [[TourOrderLastView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.tableView.frame), WIDTH, 49)];
    lastView.backgroundColor = [UIColor whiteColor];
    [lastView setTourOrderLastView:self.tourOrderLastViewLayout];
    lastView.priceLabel.text = [NSString stringWithFormat:@"总额：¥ %.2f",[self.price floatValue]];
    lastView.lastViewPayButton = ^() {
        /*
         username=15757831711 用户名
         travel_date=2017-04-19 游玩日期
         realname=张三 取票人姓名
         mobile=15757831716 取票人手机号
         product_id=357738 商品id
         ticket_count=2 商品数量
         sn=123456推广码(可选)
         */
        
        if (!_dataString.length) {
            [self showHint:@"请选择出行日期"];
            return ;
        }
        
        NSString *realname = ((UITextField *)self.textFieldArray.firstObject).text;
        NSString *mobile = ((UITextField *)self.textFieldArray.lastObject).text;
        
        if (!realname.length || !mobile) {
            [self showHint:@"请填写完整的个人信息"];
        }
        
        NSLog(@"%@",USERNAME);
        
        NSDictionary *params = @{
                                 @"username":USERNAME,
                                 @"travel_date":_dataString,
                                 @"realname":realname,
                                 @"mobile":mobile,
                                 @"product_id":self.replaceID,
                                 @"ticket_count":numberString,
                                 @"sn":@""
                                 };
        
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"http://test.suntao-develop.com/api/travel/create_order" completeBlock:^(id object) {
            NSLog(@"%@",object);
            if (JudgeBackDataCode) {
                NSDictionary *dict = [object objectForKey:@"data"];
                OrderPaymentController *order = [[OrderPaymentController alloc] init];
                order.OrderString = dict[@"order_no"];
                order.OrderMonryString = dict[@"pay_amount"];
                order.OrderTitleString = self.tourSellOrderTableViewCellLayout.tourSellOrderModel.title;
                order.OrderDescribeInfo = [NSString stringWithFormat:@"%@,%@",realname,mobile];
                order.orderType = @"4";
                [self.navigationController pushForm:self.navigationController pushToAndHidden:order];
            } else {
                [self showHint:[NSString stringWithFormat:@"%@",[object[@"message"] objectForKey:@"view"]]];
            }
        }];
        
    };
    self.priceLabel = lastView.priceLabel;
    
    [self.view addSubview:lastView];
    
    self.title = @"景点预定";
    _judgeFirst = YES;
    
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 1)];
    _webView.delegate = self;
    _webView.scrollView.scrollEnabled = NO;
    [_webView loadHTMLString:self.htmlString baseURL:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeDateBtnTitle:) name:@"changBtnSelected" object:nil];
}

-(void)countPrice
{
    double price = [self.price doubleValue];
    
    CGFloat totlePrice = price * [numberString floatValue];
    
    self.priceLabel.text = [NSString stringWithFormat:@"总额：¥%.2f",totlePrice];
    
}
- (void)changeDateBtnTitle:(NSNotification *)noti {
    _dataString = noti.userInfo[@"SelectedTime"];
    
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:1 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - Table view data source

- (void)resignFirstResponderTextFieldArray {
    for (UITextField *textField in self.textFieldArray) {
        [textField resignFirstResponder];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self resignFirstResponderTextFieldArray];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self resignFirstResponderTextFieldArray];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0.1;
    } else {
        return 10;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    } else if(section == 1) {
        return 2;
    } else {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0) {
        return kTourDetailHeaderHeight;
    } else if (indexPath.section == 2) {
        return _webView.frame.size.height;
    } else {
        return 44;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            TourSellerDetailView *headerView = [[TourSellerDetailView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, kTourDetailHeaderHeight)];
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"header"];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"header"];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            [headerView setDetailHeaderViewWithModel:self.tourDetailHeaderLayout];
            [headerView.phoneButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
            [headerView.phoneButton setTitle:[NSString stringWithFormat:@"¥ %@",self.price] forState:UIControlStateNormal];
            [headerView.phoneButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
            headerView.phoneButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            headerView.phoneButton.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
            headerView.phoneButton.titleLabel.font = [UIFont systemFontOfSize:18];
            headerView.addressButton.hidden = YES;
            if (_judgeFirst) {
                _judgeFirst = NO;
                [cell.contentView addSubview:headerView];
            }
            [headerView.leftImg sd_setImageWithURL:[NSURL URLWithString:self.tourSellOrderTableViewCellLayout.tourSellOrderModel.picurl] placeholderImage:[UIImage imageNamed:@"icon_NoRecord"]];
//            headerView.nameLabel.text = self.tourSellOrderTableViewCellLayout.tourSellOrderModel.title;
//            headerView.nameLabel.Height = 30;
//            headerView.nameLabel.y = 0;
//            headerView.nameLabel.width = headerView.detailLabel.width;
//            if(iPhone5 || iPhone6) {
//                headerView.nameLabel.font = [UIFont systemFontOfSize:12];
//            } else {
//                headerView.nameLabel.font = [UIFont systemFontOfSize:13];
//            }
//            headerView.nameLabel.numberOfLines = 2;

            headerView.detailLabel.text = self.tourSellOrderTableViewCellLayout.tourSellOrderModel.title;
            headerView.nameLabel.text = @"";
            headerView.detailLabel.font = [UIFont systemFontOfSize:16];
            
            return cell;
//            return nil;
        } else if (indexPath.row == 1) {
            TourSellerOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"chooseData"];
            if (!cell) {
                cell = [[TourSellerOrderTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"chooseData" andTableViewCellConentViewStyle:UITableViewCellConentViewStyleData];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            [cell setHeaderViewLayout:self.tourSellOrderTableViewCellLayout andTableViewCellConentViewStyle:UITableViewCellConentViewStyleData andLeftLabelString:@"使用日期:"];
            NSLog(@"%@",_dataString);
            [cell.dataButton setTitle:_dataString.length ? _dataString : @"请选择出行日期" forState:UIControlStateNormal];
            self.dataButton = cell.dataButton;
            
             __weak typeof(self) weakself = self;
            
            cell.chooseDataButton = ^(UIButton *button) {
                [self resignFirstResponderTextFieldArray];
                if (button.selected == YES) {
                    [weakself.dateVC showDateView:button.tag];
                    button.selected = NO;
                } else {
                    [weakself.dateVC backDateView:button.tag];
                    button.selected = YES;
                }

                NSLog(@"%@",[NSNumber numberWithBool:button.selected]);
            };
            
            return cell;
        } else {
            TourSellerOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cutAndAdd"];
            if (!cell) {
                cell = [[TourSellerOrderTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cutAndAdd" andTableViewCellConentViewStyle:UITableViewCellConentViewStyleCutAndAdd];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            [cell setHeaderViewLayout:self.tourSellOrderTableViewCellLayout andTableViewCellConentViewStyle:UITableViewCellConentViewStyleCutAndAdd andLeftLabelString:@"购买份数:"];
            
            __block TourSellerOrderTableViewCell *weakCell = cell;
            
            cell.numCutBlock = ^() {
                [self resignFirstResponderTextFieldArray];
                NSInteger count = [weakCell.numberLabel.text integerValue];
                count--;
                if(count <= 0){
                    return ;
                }
                NSString *numStr = [NSString stringWithFormat:@"%ld",(long)count];
                
                weakCell.numberLabel.text = numStr;
                numberString = numStr;
                
                [self countPrice];
            };
            
            cell.numAddBlock = ^() {
                [self resignFirstResponderTextFieldArray];
                NSInteger count = [weakCell.numberLabel.text integerValue];
                count++;
                NSString *numStr = [NSString stringWithFormat:@"%ld",(long)count];
                
                weakCell.numberLabel.text = numStr;
                numberString = numStr;

                [self countPrice];
            };
            
            return cell;
        }
    } else if (indexPath.section == 1) {
        TourSellerOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"default"];
        if (!cell) {
            cell = [[TourSellerOrderTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"default" andTableViewCellConentViewStyle:UITableViewCellConentViewStyleDefault];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        [cell setHeaderViewLayout:self.tourSellOrderTableViewCellLayout andTableViewCellConentViewStyle:UITableViewCellConentViewStyleDefault andLeftLabelString:@""];
        
        if (indexPath.row == 0) {
            cell.leftLabel.text = @"取票人:";
            cell.inputTextField.placeholder = @"输入取票人姓名";
        } else {
            cell.leftLabel.text = @"联系电话:";
            cell.inputTextField.placeholder = @"输入联系电话";
            cell.inputTextField.keyboardType = UIKeyboardTypePhonePad;
        }
        [self.textFieldArray addObject:cell.inputTextField];
        return cell;
    } else {
        static NSString *identifier = @"web";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell){
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            [cell.contentView addSubview:_webView];
            /* 忽略点击效果 */
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        return cell;
    }
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
    self.webView.frame = CGRectMake(self.webView.frame.origin.x,self.webView.frame.origin.y, WIDTH, height);
    [self.tableView reloadData];
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"webViewDidStartLoad");
}


- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    NSLog(@"didFailLoadWithError===%@", error);
}

- (DateViewController *)dateVC {
    
    if (!_dateVC) {
        _dateVC = [[DateViewController alloc] init];
    }
    return _dateVC;
}

- (NSMutableArray *)textFieldArray {
    if (!_textFieldArray) {
        _textFieldArray = [NSMutableArray array];
    }
    return _textFieldArray;
}
@end
